
# -*- coding: UTF-8 -*-
import os, sys
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
PKG_PATH = CUR_PATH[0:CUR_PATH.rindex('\\')]
sys.path.append(PKG_PATH)

from db_interface import db_interface
from scipy import stats
from public_func.exchange_date import cal_stock_exchange_date
import datetime
from a_hold_stock_buy import stock_mkv_data

## 行业轮动



def sh_percent_data():
    start_date, end_date = cal_stock_exchange_date(34)
    sql_sh = f"select date, now from sh_days_data where date between '{start_date}' and '{end_date}'" \
             f"order by date desc"
    sql_data = list(db_interface.stock_base.select(sql_sh))
    price_list = [x[1] for x in sql_data]
    date = sql_data[0][0].strftime("%Y-%m-%d")
    price = price_list[0]
    price_per = stats.percentileofscore(price_list, price)

    return date, price, '%.2f'% price_per


def indus_stock_rank(indus="文化传媒", sort="mkv"):
    def ids_contain_stock():
        sql_ids = f"select stock from ids_stock_list where ids_name = '{indus}'"
        ids_data = list(db_interface.stock_base.select(sql_ids))
        stock_sh = [x[0] for x in ids_data if x[0].startswith("6")]
        stock_sz = [x[0] for x in ids_data if not x[0].startswith("6")]
        return stock_sh, stock_sz

    stock_sh, stock_sz = ids_contain_stock()
    if not stock_sz + stock_sz:
        return []
    date_interval = cal_stock_exchange_date(34)
    sql_stock = f"select code, name, date, now from stock_days_sh where date in {tuple(date_interval)} and " \
             f"code in {tuple(stock_sh)} union " \
             f"select code, name, date, now from stock_days_sz where date in {tuple(date_interval)} and " \
             f"code in {tuple(stock_sz)} " \
             f"order by date desc"
    if len(stock_sz) == 1:
        sql_stock = f"select code, name, date, now from stock_days_sh where date in {tuple(date_interval)} and " \
                    f"code in {tuple(stock_sh)} union " \
                    f"select code, name, date, now from stock_days_sz where date in {tuple(date_interval)} and " \
                    f"code = '{stock_sz[0]}' " \
                    f"order by date desc"
    stock_data = db_interface.stock_base.select(sql_stock)
    stock_dict = {}
    for item in stock_data:
        code, name, date, price = item
        date = date.strftime("%Y-%m-%d")
        if code not in stock_dict:
            stock_dict[code] = []
        stock_dict[code].append(
            (name, date, price)
        )
    result = []
    stock_mkv = stock_mkv_data(mkv=10)
    for stock, info in stock_dict.items():
        price, change_pct =0, 0
        if len(info) == 2:
            price = info[0][2]
            change_pct = info[0][2]/info[1][2] - 1
        mkv = stock_mkv[stock][1] if stock in stock_mkv else -1
        result.append({
            "name": info[0][0],
            "code": stock,
            "price": price,
            "change_pct": round(100*change_pct, 2),
            "mkv": mkv
        })
    if sort == "price":
        sort_str = "change_pct"
    elif sort == "mkv":
        sort_str = "mkv"
    result = sorted(result, key=lambda x: x[sort_str], reverse=True)

    return result[:6]



def indus_data_rank(sort=True):
    sql_str = "asc" if sort else "desc"
    sql = 'select date, `rank`, name, changepct_bef from dongcai_ids_data where date = ' \
          '(select max(date) from dongcai_ids_data) order by `rank`' + sql_str
    sql_data = list(db_interface.stock_base.select(sql))
    date = sql_data[0][0].strftime("%Y-%m-%d")
    result = []
    for item in sql_data:
        result.append({
            "rank": item[1],
            "name": item[2],
            "change_pct": round(item[3], 2)
        })

    return date, result


def find_etf_change(sort=True):
    date, price, percent = sh_percent_data()
    weekday = datetime.datetime.strptime(date, "%Y-%m-%d").weekday()
    # r = have_stock_pe_percent(stock_list)
    print('==========')
    print(f"今天是:{date}; 周 {str(weekday + 1)}")
    print(f"大盘点位：{price}，{percent}百分位")
    print('++++++++++')
    indus_date, rank = indus_data_rank(sort=sort)  # sort:False，机会
    print(f"行业的最新日期是：{indus_date}")
    index = 0
    for i, item in enumerate(rank[:]):
        ids_stock = indus_stock_rank(indus=item['name'], sort="mkv")  ## price：change_pct
        if ids_stock:
            print(f"{index + 1}，{item}该行业的股票：")
            index += 1
            for stock in ids_stock:
                print(stock)
            print('---------')
            if index >= 100:
                break

def get_stock_ids(stock_code):
    sql = f"select code, ids, mkv from stock_info where code in {tuple(stock_code)}"
    query = db_interface.stock_base.select(sql)
    res = {}
    for item in query:
        code, ids, mkv = item
        res[code] = {
            "ids": ids,
            "mkv": mkv
        }

    return res



def find_eft_yeji():
    date_7days = datetime.datetime.now() - datetime.timedelta(days=15)
    sql = "select date, code, name, predict_finance, add_amp_lower, predict_content, reason_explain from  basic_finance_yeji " \
          "where date >= " + f"'{date_7days.strftime('%Y-%m-%d')}'"
    # print(sql)
    query = list(db_interface.stock_base.select(sql))
    stock_list = [x[1] for x in query]
    stock_ids_dict = get_stock_ids(stock_list)
    ids_data = {}
    for item in query:
        date, code, name, predict_finance, add_amp_lower, predict_content, reason_explain = item
        ids, mkv = '', 0
        if code in stock_ids_dict:
            ids = stock_ids_dict[code]['ids']
            mkv = stock_ids_dict[code]['mkv']
        date = date.strftime("%Y-%m-%d")
        if predict_finance == "扣除非经常性损益后的净利润":
            if ids not in ids_data:
                ids_data[ids] = []
            ids_data[ids].append((name, code, f"业绩：{add_amp_lower}",  f"市值：{mkv}亿", date, predict_content, reason_explain))
    res = []
    for k, v in ids_data.items():
        rise = [x for x in v if float(x[2][3:]) > 0]
        down = [x for x in v if float(x[2][3:]) < 0]
        ratio = len(rise) / len(v)
        res.append({
            "ids": k,
            "sum": len(v),
            "ratio": round(ratio, 2),
            "detail": {
                "rise": sorted(rise, key=lambda x: float(x[2][3:]), reverse=True),
                "down": sorted(down, key=lambda x: float(x[2][3:]), reverse=True)
            }
        })
    res = sorted(res, key=lambda x: x['sum'], reverse=True)
    for i, item in enumerate(res):
        print(i+1, item['ids'], item['sum'], item['ratio'])
        for d in item['detail']['rise']:
            print(d)
        for d in item['detail']['down']:
            print(d)
        print('--------')







if __name__ == "__main__":
    find_etf_change(sort=True)
    # find_eft_yeji()



